//
//  HelloWorldLayer.m
//  pipi
//
//  Created by zhao ys on 5/10/11.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//


// Import the interfaces
#import "playLayer.h"
#import "pauseLayer.h"
#import "scoreLayer.h"
#import "SoundManager.h"

// HelloWorldLayer implementation
@implementation PlayLayer

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	PlayLayer *layer = [PlayLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];
		
		_button_loud = [CCSprite spriteWithFile:@"l.png"];
		_button_silent = [CCSprite spriteWithFile:@"s.png"];
		
		_button_loud.position = ccp(10 + _button_loud.contentSize.width / 2,  20 + _button_loud.contentSize.height / 2);
		_button_silent.position = ccp(size.width - _button_silent.contentSize.width / 2 - 10, 20 + _button_silent.contentSize.height / 2);
		
		
		[self addChild:_button_loud];
		[self addChild:_button_silent];
	
		
		CCMenuItem * pause = [CCMenuItemImage itemFromNormalImage:@"pause.png" selectedImage:@"pause.png"
														   target:self selector:@selector(OnPause:)];
		
		CGSize pauseSize = pause.contentSize;
		pause.position = ccp(size.width - pauseSize.width / 2, size.height - pauseSize.height / 2);
		CCMenu * menu = [CCMenu menuWithItems:pause, nil];
		menu.position = ccp(0,0);
		[self addChild:menu];
		
		self.isTouchEnabled = YES;
		
		[self scheduleUpdate];

	
		CCSprite * _pi_sprite = [CCSprite spriteWithFile:@"240.png"];
        _pi_prog = [CCProgressTimer progressWithFile:@"240.png" ];
        _pi_prog.type = kCCProgressTimerTypeHorizontalBarLR;
        CGSize s = _pi_prog.contentSize;
        _pi_prog.position = ccp(100 + s.width / 2, 70);
        _pi_prog.sprite.color = ccc3(255,0,0);
        _pi_sprite.position = ccp(100 + s.width / 2, 70);
        [self addChild:_pi_sprite];
        [self addChild:_pi_prog];

        CCSprite * _silent_sprite = [CCSprite spriteWithFile:@"160.png"];
        _silent_prog = [CCProgressTimer progressWithFile:@"160.png"];
        _silent_prog.type = kCCProgressTimerTypeHorizontalBarLR;
        s = _silent_prog.contentSize;
        _silent_prog.position = ccp(100 + s.width/2, 40);
        _silent_prog.sprite.color = ccc3(200,100,0);
        _silent_sprite.position = ccp(100 + s.width/2, 40);
        [self addChild:_silent_sprite];
        [self addChild:_silent_prog];
		
		
		_silent_prog.percentage = 0.f;
        _pi_prog.percentage = 0.f;
		
        srand((unsigned int)time(0));
        _fly_sep_max = 3;
        _fly_sep_min = 0.5;
		
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"dragon.plist"];
		
        CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dragon_0_0.png"];
        _plane = [CCSprite spriteWithSpriteFrame:frame];
		
        CGSize planeSize = _plane.contentSize;
        _plane.position = ccp(-planeSize.width/2, 250);
        _plane.visible = NO;
        [self addChild:_plane];

		
		int i, j;
		for(j = 0; j < 7; j++) {
            NSMutableArray *frames = [NSMutableArray arrayWithObjects:nil];
            for(i = 0; i < 9; i++) {
	    	NSString * name = [NSString stringWithFormat:@"dragon_%d_%d.png", i, j];
                CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
                [frames addObject:frame];
            }
			
            NSString * animation_name = [NSString stringWithFormat:@"plan_%d", j];
            [[CCAnimationCache sharedAnimationCache] addAnimation:[CCAnimation animationWithFrames:frames delay:0.1f] name:animation_name];
        }
		
        _label = [CCLabelTTF labelWithString:@"" fontName:@"Marker Felt" fontSize:32];
        _label.position = ccp(size.width/2, 300);
        [self addChild:_label];
		
        _fly_sep_left = 1; //rand() % (int)(_fly_sep_max - _fly_sep_min) + _fly_sep_min;
		
        _pi_max = 1000;
        _silent_max = 300;
		
        _pi_inc_speed = 90;
        _silent_inc_speed = 30;
        _loud_dec_speed = 140;
        _silent_dec_speed = 170;
		
        _pi = 0;
        _silent_left = 0;
		
        _loud = 0;
        _silent = 0;
        _score = 0;

		[[SoundManager sharedManager] play:@"background" loops:-1];		
	}
	return self;
}

-(void)OnPause:(id)sender {
	[[SoundManager sharedManager] stop:@"background"];

	
	[[CCDirector sharedDirector] pause];		
	// 1. 一个 CCRenderTexture 用以存储当前场景(你就是要在这上面弹出界面)的界面
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
	[renderTexture begin];
	[self visit];
	[renderTexture end];
	[renderTexture setPosition:ccp(winSize.width/2, winSize.height/2)];
	//2. pauseScene 是要弹出的界面场景，看起来还有上一个界面，实际上已经切换了一个场景
	CCScene* pauseScene = [CCScene node];
	// 3. 一个 CCLayerColor/CCColorLayer （这两个一样） 用以在上一个界面覆盖一层, 实现暗灰效果
	CCLayerColor* colorLayer = [CCColorLayer layerWithColor:ccc4(0, 0, 0, 128)];
	// pauseScene 的组成：从底层向外层： 上一个界面截图，暗灰效果层, 新的弹出菜单层。
	[pauseScene addChild:renderTexture];
	[pauseScene addChild:colorLayer];
	[pauseScene addChild:[pauseLayer node]];
	// 4. 直接 push 过去吧，方便存储当前场景状态之类的
	[[CCDirector sharedDirector] pushScene:pauseScene];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	
	[super dealloc];
}

-(BOOL) buttonTouched:(UITouch * ) touch button:(CCSprite*)sprite {
	CGPoint touchLocation = [touch locationInView: [touch view]];
	touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
	CGPoint pt = [sprite convertToNodeSpace:touchLocation];
	CGRect r = sprite.textureRect;
	r.origin = CGPointZero;
	if (CGRectContainsPoint(r, pt)) {
		return YES;
	}
	return FALSE;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {
		if ([self buttonTouched:touch button:_button_loud]) {
			_loud = 1;
		}
	
		if ([self buttonTouched:touch button:_button_silent]) {
			_silent = 1;
		}
	}
}


- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {		
		if (![self buttonTouched:touch button:_button_loud]) {
			_loud = 0;
		} else if (_loud == 0) {
			_loud = 1;
		}
		
		if (![self buttonTouched:touch button:_button_silent]) {
			_silent = 0;
		} else if (_silent == 0) {
			_silent = 1;
		}
	}	
}


- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {		
		if ([self buttonTouched:touch button:_button_loud]) {
			_loud = 0;
		} 
	
		if ([self buttonTouched:touch button:_button_silent]) {
			_silent = 0;
		} 
	}
}

- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {		
		if ([self buttonTouched:touch button:_button_loud]) {
			_loud = 0;
		} 
		
		if ([self buttonTouched:touch button:_button_silent]) {
			_silent = 0;
		} 
	}
}

-(void) on_move_done {
    _plane.visible = NO;
    _fly_sep_left =  1; //rand() % (int)(_fly_sep_max - _fly_sep_min) + _fly_sep_min;
}

-(void) update:(ccTime)deltaTime {
	ccTime t = deltaTime;
	if (_fly_sep_left > 0) {
        _fly_sep_left -= t;
        if (_fly_sep_left <= 0) {
            CGSize planeSize = _plane.contentSize;
            _plane.position = ccp(-planeSize.width/2, 250);
            _plane.visible = YES;
			
            float delay = (int)((rand() * 3.9) / RAND_MAX + 1.0f);
            CGSize size = [[CCDirector sharedDirector] winSize];
			
            NSString * animation_name = [NSString stringWithFormat:@"plan_%d", rand() % 7];
            CCAnimate * animate = [CCAnimate actionWithAnimation:[[CCAnimationCache sharedAnimationCache] animationByName:animation_name]];
            [_plane runAction:[CCRepeatForever actionWithAction:animate]];
			
            CCMoveTo * move = [CCMoveTo actionWithDuration:delay position:ccp(size.width + planeSize.width/2, 250)];
            CCCallFunc * func = [CCCallFunc actionWithTarget:self selector:@selector(on_move_done)];
			
			[_plane runAction:[CCSequence actions:move, func, nil]];
        }
    }
	

	char szScore[256] = {0};
	
    _pi += t * _pi_inc_speed;
	
    if (_fly_sep_left > 0 && _loud) {
        sprintf(szScore, "%d failed", (int)_score);
        //_label.string = [NSString stringWithFormat:@"%d failed", (int)_score];
		[[SoundManager sharedManager] stop:@"background"];
		[[CCDirector sharedDirector] replaceScene:[scoreLayer sceneWithScore:_score]];
        return;
    }	

	if (_pi > 0) {
		if (_silent) {
			if (_silent_left > 0) {
				_pi -= t * _silent_dec_speed;
				_score += t * _silent_dec_speed;
				if (_pi < 0) { _pi = 0; }
				_silent_left -=  t * _silent_dec_speed;
				if (_silent_left < 0) {_silent_left = 0;}
			}
		} else if (_loud) {
			_pi -= t * _loud_dec_speed;
			_score += t * _silent_dec_speed;
			if (_pi < 0) { _pi = 0; }
			_silent_left += t * _silent_inc_speed;
			if (_silent_left >= _silent_max) {
				_silent_left = _silent_max;
			}
		}
	}
	
    sprintf(szScore, "%d", (int)_score);
    _label.string = [NSString stringWithFormat:@"%d", (int)_score];
	
    _silent_prog.percentage = _silent_left * 100/_silent_max;
    _pi_prog.percentage = _pi * 100/_pi_max;
	
	if (_pi >= _pi_max) {
        _pi = _pi_max;
		[[SoundManager sharedManager] stop:@"background"];
		[[CCDirector sharedDirector] replaceScene:[scoreLayer sceneWithScore:_score]];
		return;
    }

}




@end
